// Global instance
let webCanvas = null;

// Initialize WebCanvas
function initializeWebCanvas() {
  if (webCanvas) return; // Prevent multiple initializations
  
  try {
    webCanvas = new WebCanvas();
    console.log('WebCanvas initialized successfully');
  } catch (error) {
    console.error('Failed to initialize WebCanvas:', error);
  }
}

// Message handler
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  console.log('Received message:', message);
  
  try {
    if (!message || !message.action) {
      throw new Error('Invalid message format');
    }

    // Handle checkConnection action
    if (message.action === 'checkConnection') {
      sendResponse({ success: true });
      return true;
    }

    // Ensure WebCanvas is initialized
    if (!webCanvas) {
      initializeWebCanvas();
    }

    // Handle other actions
    switch (message.action) {
      case 'toggleCanvas':
        webCanvas.toggleCanvas(message.enabled);
        sendResponse({ success: true });
        break;
        
      case 'changeTool':
        webCanvas.setTool(message.tool);
        sendResponse({ success: true });
        break;
        
      case 'changeColor':
        webCanvas.setColor(message.color);
        sendResponse({ success: true });
        break;
        
      case 'undo':
        webCanvas.undo();
        sendResponse({ success: true });
        break;
        
      case 'redo':
        webCanvas.redo();
        sendResponse({ success: true });
        break;
        
      case 'clearCanvas':
        webCanvas.clearCanvas();
        sendResponse({ success: true });
        break;
        
      case 'saveCanvas':
        webCanvas.saveCanvas();
        sendResponse({ success: true });
        break;
        
      default:
        console.error('Unknown action:', message.action);
        throw new Error('Unknown action: ' + message.action);
    }
  } catch (error) {
    console.error('Error handling message:', error);
    sendResponse({ success: false, error: error.message });
  }
  
  return true; // Keep message channel open for async response
});

// Initialize on document load
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', initializeWebCanvas);
} else {
  initializeWebCanvas();
}

class WebCanvas {
  constructor() {
    // 初始化基本属性
    this.enabled = false;
    this.currentTool = 'pen';
    this.currentColor = '#FF0000';
    this.isDrawing = false;
    this.lastX = 0;
    this.lastY = 0;
    this.drawingHistory = [];
    this.currentHistoryStep = -1;
    this.maxHistorySteps = 50;
    this.drawingClass = 'drawing';
    
    // 初始化画布
    this.initializeCanvas();
  }

  initializeCanvas() {
    try {
      // 创建画布
      this.canvas = document.createElement('canvas');
      this.canvas.style.position = 'fixed';
      this.canvas.style.top = '0';
      this.canvas.style.left = '0';
      this.canvas.style.width = '100%';
      this.canvas.style.height = '100%';
      this.canvas.style.pointerEvents = 'none';
      this.canvas.style.zIndex = '9999';
      this.canvas.style.touchAction = 'none';
      this.canvas.dataset.tool = this.currentTool;

      // 获取上下文
      this.ctx = this.canvas.getContext('2d');
      if (!this.ctx) {
        throw new Error('Failed to get canvas context');
      }

      // 设置设备像素比
      this.scale = window.devicePixelRatio || 1;
      
      // 设置画布大小
      this.resizeCanvas();
      
      // 添加事件监听器
      window.addEventListener('resize', () => this.resizeCanvas());
      this.setupDrawingListeners();
      
      // 加载保存的状态
      this.loadSavedState();
      
      console.log('WebCanvas initialized successfully');
    } catch (error) {
      console.error('Failed to initialize canvas:', error);
      throw error;
    }
  }

  resizeCanvas() {
    try {
      // 保存当前绘画
      let oldCanvas = null;
      if (this.ctx) {
        oldCanvas = this.canvas.toDataURL();
      }
      
      // 更新设备像素比
      this.scale = window.devicePixelRatio || 1;
      
      // 设置物理像素大小
      this.canvas.width = window.innerWidth * this.scale;
      this.canvas.height = window.innerHeight * this.scale;
      
      // 设置CSS像素大小
      this.canvas.style.width = window.innerWidth + 'px';
      this.canvas.style.height = window.innerHeight + 'px';
      
      // 缩放上下文以匹配设备像素比
      this.ctx.scale(this.scale, this.scale);
      
      // 恢复之前的绘画
      if (oldCanvas) {
        const img = new Image();
        img.onload = () => {
          this.ctx.drawImage(img, 0, 0);
        };
        img.src = oldCanvas;
      }
    } catch (error) {
      console.error('Failed to resize canvas:', error);
    }
  }

  loadSavedState() {
    chrome.storage.local.get(['canvasState'], (result) => {
      if (result.canvasState) {
        const img = new Image();
        img.onload = () => {
          this.ctx.drawImage(img, 0, 0);
        };
        img.src = result.canvasState;
      }
    });
  }

  saveCurrentState() {
    try {
      const state = this.canvas.toDataURL();
      chrome.storage.local.set({ canvasState: state });
    } catch (error) {
      console.error('Failed to save canvas state:', error);
    }
  }

  setupDrawingListeners() {
    // Mouse events
    this.canvas.addEventListener('mousedown', (e) => {
      if (!this.enabled) return;
      this.startDrawing(e.clientX, e.clientY);
    });

    this.canvas.addEventListener('mousemove', (e) => {
      if (!this.isDrawing || !this.enabled) return;
      this.draw(e.clientX, e.clientY);
    });

    this.canvas.addEventListener('mouseup', () => this.stopDrawing());
    this.canvas.addEventListener('mouseleave', () => this.stopDrawing());

    // Touch events
    this.canvas.addEventListener('touchstart', (e) => {
      if (!this.enabled) return;
      e.preventDefault();
      const touch = e.touches[0];
      this.startDrawing(touch.clientX, touch.clientY);
    });

    this.canvas.addEventListener('touchmove', (e) => {
      if (!this.isDrawing || !this.enabled) return;
      e.preventDefault();
      const touch = e.touches[0];
      this.draw(touch.clientX, touch.clientY);
    });

    this.canvas.addEventListener('touchend', () => this.stopDrawing());
    this.canvas.addEventListener('touchcancel', () => this.stopDrawing());

    // Add keyboard shortcuts
    document.addEventListener('keydown', (e) => {
      if (!this.enabled) return;
      
      if (e.ctrlKey || e.metaKey) {
        if (e.key === 'z') {
          e.preventDefault();
          this.undo();
        } else if (e.key === 'y' || (e.shiftKey && e.key === 'z')) {
          e.preventDefault();
          this.redo();
        }
      }
    });
  }

  startDrawing(x, y) {
    this.isDrawing = true;
    [this.lastX, this.lastY] = [x, y];
    this.ctx.beginPath();
    this.ctx.moveTo(this.lastX, this.lastY);
    this.canvas.classList.add(this.drawingClass); // 添加绘画状态类
  }

  stopDrawing() {
    if (this.isDrawing) {
      this.isDrawing = false;
      this.canvas.classList.remove(this.drawingClass); // 移除绘画状态类
      this.saveDrawingState();
    }
  }

  draw(x, y) {
    this.ctx.beginPath();
    this.ctx.moveTo(this.lastX, this.lastY);
    this.ctx.lineTo(x, y);
    
    // 更新工具状态
    this.canvas.dataset.tool = this.currentTool;
    
    switch (this.currentTool) {
      case 'pen':
        this.ctx.globalCompositeOperation = 'source-over';
        this.ctx.strokeStyle = this.currentColor;
        this.ctx.lineWidth = 2;
        break;
      case 'highlighter':
        this.ctx.globalCompositeOperation = 'multiply';
        this.ctx.strokeStyle = this.currentColor;
        this.ctx.lineWidth = 10;
        this.ctx.globalAlpha = 0.5;
        break;
      case 'eraser':
        this.ctx.globalCompositeOperation = 'destination-out';
        this.ctx.strokeStyle = 'rgba(0,0,0,1)';
        this.ctx.lineWidth = 20;
        break;
      default:
        console.warn('Unknown tool:', this.currentTool);
        return;
    }
    
    this.ctx.lineCap = 'round';
    this.ctx.lineJoin = 'round';
    this.ctx.stroke();
    this.ctx.globalAlpha = 1.0; // Reset alpha
    
    [this.lastX, this.lastY] = [x, y];
  }

  saveDrawingState() {
    // Remove any states after current step if we're in middle of history
    if (this.currentHistoryStep < this.drawingHistory.length - 1) {
      this.drawingHistory = this.drawingHistory.slice(0, this.currentHistoryStep + 1);
    }

    // Save current canvas state
    const state = this.canvas.toDataURL();
    this.drawingHistory.push(state);
    
    // Remove oldest state if we exceed max history
    if (this.drawingHistory.length > this.maxHistorySteps) {
      this.drawingHistory.shift();
    }
    
    this.currentHistoryStep = this.drawingHistory.length - 1;
    this.saveCurrentState(); // Save to chrome.storage
    
    // Notify popup about history state change
    chrome.runtime.sendMessage({
      action: 'updateHistory',
      canUndo: this.currentHistoryStep > 0,
      canRedo: this.currentHistoryStep < this.drawingHistory.length - 1
    }).catch(error => {
      // Ignore errors when popup is closed
      if (!error.message.includes('receiving end does not exist')) {
        console.error('Failed to update history state:', error);
      }
    });
  }

  undo() {
    if (this.currentHistoryStep > 0) {
      this.currentHistoryStep--;
      this.loadHistoryState();
    }
  }

  redo() {
    if (this.currentHistoryStep < this.drawingHistory.length - 1) {
      this.currentHistoryStep++;
      this.loadHistoryState();
    }
  }

  loadHistoryState() {
    const state = this.drawingHistory[this.currentHistoryStep];
    if (state) {
      const img = new Image();
      img.onload = () => {
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        this.ctx.drawImage(img, 0, 0);
        
        // Notify popup about history state change
        chrome.runtime.sendMessage({
          action: 'updateHistory',
          canUndo: this.currentHistoryStep > 0,
          canRedo: this.currentHistoryStep < this.drawingHistory.length - 1
        }).catch(error => {
          // Ignore errors when popup is closed
          if (!error.message.includes('receiving end does not exist')) {
            console.error('Failed to update history state:', error);
          }
        });
      };
      img.src = state;
    }
  }

  clearCanvas() {
    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
    this.saveDrawingState();
  }

  async saveCanvas() {
    try {
      // 创建一个新的临时画布
      const tempCanvas = document.createElement('canvas');
      tempCanvas.width = window.innerWidth * this.scale;
      tempCanvas.height = window.innerHeight * this.scale;
      const tempCtx = tempCanvas.getContext('2d');

      // 截取网页内容
      const pageCanvas = await html2canvas(document.body, {
        scale: this.scale,
        width: window.innerWidth,
        height: window.innerHeight,
        scrollX: window.pageXOffset,
        scrollY: window.pageYOffset,
        x: window.pageXOffset,
        y: window.pageYOffset,
        backgroundColor: '#ffffff',
        logging: false,
        useCORS: true,
        allowTaint: true
      });

      // 绘制网页内容
      tempCtx.drawImage(pageCanvas, 0, 0);

      // 绘制用户的画布内容
      tempCtx.drawImage(this.canvas, 0, 0);

      // 创建下载链接
      const link = document.createElement('a');
      const timestamp = new Date().toISOString().slice(0, 19).replace(/[:]/g, '-');
      link.download = `web-canvas-${timestamp}.png`;
      link.href = tempCanvas.toDataURL('image/png');
      link.click();

      console.log('Canvas saved successfully');
    } catch (error) {
      console.error('Failed to save canvas:', error);
      throw error;
    }
  }

  setTool(tool) {
    this.currentTool = tool;
    this.canvas.dataset.tool = tool;
  }

  setColor(color) {
    this.currentColor = color;
  }

  saveAsImage() {
    this.saveCanvas();
  }

  toggleCanvas(enabled) {
    try {
      this.enabled = enabled;
      
      if (enabled && !document.body.contains(this.canvas)) {
        document.body.appendChild(this.canvas);
        this.canvas.style.pointerEvents = 'auto';
        document.body.classList.add(this.drawingClass);
      } else if (!enabled && document.body.contains(this.canvas)) {
        this.canvas.style.pointerEvents = 'none';
        document.body.classList.remove(this.drawingClass);
      }
      
      // 保存状态
      chrome.storage.local.set({ enabled: this.enabled });
      
      console.log('Canvas toggled:', enabled);
    } catch (error) {
      console.error('Failed to toggle canvas:', error);
      throw error;
    }
  }
}
